//
//  MCTableViewBaseViewController.swift
//  UITableViewDemo
//
//  Created by daqsoft-mac on 2022/5/11.
//

import UIKit

class MCTableViewBaseViewController: MCBaseViewController {
    
    /// 懒加载TableView
    lazy var tableView : UITableView = {
        let tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), style: .plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.estimatedRowHeight = 50
        tableView.rowHeight = UITableView.automaticDimension
        tableView.separatorStyle = .none
        tableView.estimatedSectionFooterHeight = 50
        tableView.estimatedSectionHeaderHeight = 50
        tableView.tableHeaderView = UIView.init()
        tableView.tableFooterView = UIView.init()
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        self.view.addSubview(tableView)
        return tableView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
}

/*
 * UITableViewDelegate代理方法
 */
extension MCTableViewBaseViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let sectionModel = self.sectionArray![indexPath.section]
        var row = indexPath.row
        if row >= sectionModel.cellNum {
            row = sectionModel.cellNum - 1
            tableView.reloadData()
        }
        let cellModel = sectionModel.cellArray[row]
        cellModel?.cellSelect(indexPath)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let sectionModel = self.sectionArray![section]
        let identifier = sectionModel.sectionHeaderProtocol?.obtainIdentifier() ?? ""
        let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: identifier)
        view?.viewProtocol = sectionModel.sectionHeaderProtocol
        return view ?? UIView.init()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        let sectionModel = self.sectionArray![section]
        return sectionModel.sectionHeaderProtocol?.obtainHeight() ?? 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let sectionModel = self.sectionArray![indexPath.section]
        var row = indexPath.row
        if row >= sectionModel.cellNum {
            row = sectionModel.cellNum - 1
            tableView.reloadData()
        }
        let cellModel = sectionModel.cellArray[row]
        return cellModel?.obtainHeight() ?? 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        let sectionModel = self.sectionArray![section]
        return sectionModel.sectionFooterProtocal?.obtainHeight() ?? 0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let sectionModel = self.sectionArray![section]
        let identifier = sectionModel.sectionFooterProtocal?.obtainIdentifier() ?? ""
        let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: identifier)
        view?.viewProtocol = sectionModel.sectionFooterProtocal
        return view ?? UIView.init()
    }
}

/*
 * UITableViewDataSource代理方法
 */
extension MCTableViewBaseViewController : UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.sectionArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 获取Section的数据模型
        let sectionModel = self.sectionArray![indexPath.section]
        // 数据异常做一次重刷
        var row = indexPath.row
        if row >= sectionModel.cellNum {
            row = sectionModel.cellNum - 1
            tableView.reloadData()
        }
        let cellModel = sectionModel.cellArray[row]
        let identifier = cellModel?.obtainIdentifier() ?? ""
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        cell?.cellProtocol = cellModel
        cell?.selectionStyle = .none
        return cell ?? UITableViewCell.init()
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.sectionArray?[section].cellNum ?? 0
    }
}

/*
 * 数据绑定扩展
 */

private var sectionArrayKey : Void?

extension MCTableViewBaseViewController {
    
    fileprivate var sectionArray : [MCPublicTableViewSectionModel]? {
        get {
            let array = objc_getAssociatedObject(self, &sectionArrayKey) as? [MCPublicTableViewSectionModel]
            return array ?? Array()
        }
        
        set {
            objc_setAssociatedObject(self, &sectionArrayKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    func addSectionModel(_ sectionModel : MCPublicTableViewSectionModel?) {
        guard let sectionModel = sectionModel else {
            return
        }
        if sectionModel.sort == -1 {
            sectionArray!.append(sectionModel)
        }
        var array = Array<MCPublicTableViewSectionModel>()
        for model in sectionArray! {
            if model.sort != sectionModel.sort {
                array.append(model)
            }
        }
        array.append(sectionModel)
        array.sort()
        sectionArray = array
    }
}
